import type { ValidatedError } from '@arco-design/web-vue'
import { createEventHook } from '@vueuse/core'
import { type Ref, ref } from 'vue'

export type FormValidateMethod = {
  validate: (
    callback?: (errors?: Record<string, ValidatedError>) => void
  ) => Promise<void | Record<string, ValidatedError>>
}

export function useArcoForm<T>(initialState: T) {
  const formState = ref(initialState) as Ref<T>

  const submit = createEventHook<T>()
  const formRef = ref<FormValidateMethod>()
  const validate = () => {
    return formRef.value?.validate((errors) => {
      errors === undefined && submit.trigger(formState.value)
    })
  }

  return {
    formRef,
    formState,
    validate,
    onValidateSuccess: submit.on
  }
}
